package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class RateActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "Rate";

    private Button btnDollar, btnEuro, btnWon;
    private EditText inputRmb;
    private TextView rmbResult;

    private float dollarRate = 0.14f, euroRate = 0.12f, wonRate = 201.81f;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        btnDollar = findViewById(R.id.btn_dollar);
        btnEuro = findViewById(R.id.btn_euro);
        btnWon = findViewById(R.id.btn_won);

        btnDollar.setOnClickListener(this::click);
        btnEuro.setOnClickListener(this::click);
        btnWon.setOnClickListener(this::click);

        inputRmb = findViewById(R.id.inputrmb);
        rmbResult = findViewById(R.id.rmb_result);

        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG, "handleMessage: 收到返回数据");
                if (msg.what == 6) {
                    Bundle b = (Bundle) msg.obj;
                    dollarRate = b.getFloat("web_dollar");
                    euroRate = b.getFloat("web_euro");
                    wonRate = b.getFloat("web_won");
                    Log.i(TAG, "handleMessage web_dollar="+dollarRate);
                    Log.i(TAG, "handleMessage web_euro="+euroRate);
                    Log.i(TAG, "handleMessage web_won="+wonRate);
                    Toast.makeText(RateActivity.this, "数据已更新", Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };

        //开启线程
        Thread t = new Thread(this);
        t.start(); //this.run()
    }

    public void click(View btn) {
        Log.i(TAG, "onCreate: 111111111");
        //获取用户输入数据
        String inputs = inputRmb.getText().toString();

        float rate = 1f;
        if (btn.getId() == R.id.btn_dollar) {
            rate = dollarRate;
        } else if (btn.getId() == R.id.btn_euro) {
            rate = euroRate;
        } else {
            rate = wonRate;
        }

        if (inputs != null && inputs.length() > 0) {
            //String-->float
            float rmb = Float.parseFloat(inputs);
            float r = rmb * rate;
            rmbResult.setText(String.valueOf(r));
        } else {
            Toast.makeText(this, "请输入数据后计算", Toast.LENGTH_SHORT).show();
        }
    }

    public static String inputStream2String(InputStream in) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;

        while ((length = in.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(StandardCharsets.UTF_8.name());
    }

    public void run() {
        Log.i(TAG, "run: 子线程运行中");
        try {
            Thread.sleep(3000);  // 睡眠3秒

            // 确保替换为有效的URL
            //URL url = new URL("https://chl.cn/huilv/?jinri");
            //HttpURLConnection http = (HttpURLConnection) url.openConnection();
            //InputStream in = http.getInputStream();
            //String html = inputStream2String(in);
            //Log.i(TAG, "run: html=" + html);


            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Log.i(TAG, "run: Title=" + doc.title());
            Elements tables = doc.getElementsByTag("table");
            Element table = tables.get(1);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);

            // 遍历行，提取数据
            for (Element tr : trs) {
                Elements tds = tr.children();
                Element td1 =tds.get(0);
                Element td2 =tds.get(5);
                String str1 =td1.text();
                String str2 =td2.text();
                Log.i(TAG, "run: "+str1+"==>"+str2);
                float r = 100f/Float.parseFloat(str2);

                if(str1.equals("美元")){
                    //美元汇率
                }

            }

        } catch (InterruptedException e) {
            Log.e(TAG, "run: Thread interrupted", e);
        } catch (MalformedURLException e) {
            Log.e(TAG, "run: Invalid URL", e);
        } catch (IOException e) {
            Log.e(TAG, "Network error occurred: ", e);
        } catch (Exception e) {
            Log.e(TAG, "run: Unexpected error", e);
        }




    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 9 && resultCode == 7) {
            Bundle bdl = data.getExtras();
            dollarRate = bdl.getFloat("dollar2");
            euroRate = bdl.getFloat("euro2");
            wonRate = bdl.getFloat("won2");

            Log.i(TAG, "onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult: euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonRate);

            // 发送消息到UI线程
            Log.i(TAG, "run: run bdl=" + bdl);
            Message msg = handler.obtainMessage(6);
            // msg.obj = "hello from msg";
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息发送完毕");
        }


    }
}
